package org.neogenesis.web.loader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.neogenesis.web.exception.NotAnalizablePlatform;

public class ProbesLoaderSOFTFile extends ProbesLoader {

	protected List<MetaColumn> metaColumns;

	private int geneValueColumn;

	public ProbesLoaderSOFTFile(String platformName, String filePath)
			throws IOException, NotAnalizablePlatform {
		rows = new LinkedList<String[]>();

		BufferedReader in = new BufferedReader(new FileReader(filePath
				+ platformName));

		String line;
		MetaColumn column;

		int i = 0;
		while ((line = in.readLine()) != null) {
			if (!line.startsWith("#"))
				break;

			String[] split = line.split("=");

			column = new MetaColumn(i, split[0].trim(), split[1].trim());
			metaColumns.add(column);
			i++;
		}
		// select the column with the gene Id
		defineFileType();

		if (typeMetaPlatform.compareTo(TypeMetaPlatform.NONE) == 0)
			throw new NotAnalizablePlatform();

		// get the data
		while ((line = in.readLine()) != null) {
			String[] split = line.split("\t");

			if (split.length == 1)
				continue;

			if (split.length -1 < geneValueColumn)
				continue;

			if (split[geneValueColumn].equalsIgnoreCase("---"))
				continue; // skip this row

			rows.add(split);
		}
		in.close();
	}

	@Override
	protected void defineFileType() {

		geneValueColumn = -1;
		typeMetaPlatform = TypeMetaPlatform.NONE;
		TypeMetaPlatform temp;

		for (int i = 0; i < metaColumns.size(); i++) {
			try {
				temp = TypeMetaPlatform.valueOf(metaColumns.get(i).key
						.toUpperCase());
				if (temp.priority() > typeMetaPlatform.priority()) {
					typeMetaPlatform = temp;
					geneValueColumn = i;
				}
			} catch (IllegalArgumentException e) {
			}
		}

	}

	@Override
	public int getIdColumn() {
		return geneValueColumn;
	}

	class MetaColumn {

		int id;
		String key;
		String description;

		public MetaColumn() {
		}

		private MetaColumn(int id, String key, String description) {
			this.id = id;
			this.key = key.replace("#", "");
			this.description = description;
		}
	}

}
